package logic

import (
	"fmt"
	"log"
	"mssgserver/constant"
	"mssgserver/db"
	"mssgserver/net"
	"mssgserver/server/common"
	"mssgserver/server/game/gameConfig"
	"mssgserver/server/game/model"
	"mssgserver/server/game/model/data"
	"mssgserver/utils"
)

var RoleService = &roleService{}

type roleService struct {
}

/*
*
查询当前登录用户的角色和角色资源等
*/
func (s *roleService) EnterServer(uid int, rspObj *model.EnterServerRsp, req *net.WsMsgReq) error {
	//1 判断当前的角色是否存在
	role := &data.Role{}
	ok, err := db.Engine.Table(role).Where("uid=?", uid).Get(role)
	if err != nil {
		log.Println("查询role表错误")
		return common.New(constant.DBError, "查询role表错误")
	}
	if !ok {
		log.Println("当前用户角色查询不到:", uid)
		return common.New(constant.RoleNotExist, fmt.Sprintf("当前用户角色查询不到:%d", uid))
	}
	//2 判断角色的资源是否存在,没有则创建默认资源
	rid := role.RId
	roleRes := &data.RoleRes{}
	ok, err = db.Engine.Table(roleRes).Where("rid=?", rid).Get(roleRes)
	if err != nil {
		log.Println("查询roleRes表错误")
		return common.New(constant.DBError, "查询roleRes表错误")
	}
	if !ok {
		//没有则创建默认的roleRes的数据
		roleRes.RId = rid
		roleRes.Decree = gameConfig.Base.Role.Decree
		roleRes.Gold = gameConfig.Base.Role.Gold
		roleRes.Grain = gameConfig.Base.Role.Grain
		roleRes.Iron = gameConfig.Base.Role.Iron
		roleRes.Stone = gameConfig.Base.Role.Stone
		roleRes.Wood = gameConfig.Base.Role.Wood
	}
	roleModel := role.ToModel().(model.Role)
	roleResModel := roleRes.ToModel().(model.RoleRes)
	//3rid生成token等
	token, err := utils.Award(rid)
	if err != nil {
		log.Println("EnterServer生成token出错", err)
		return common.New(constant.SessionInvalid, "EnterServer生成token出错")
	}
	rspObj.Time = 0
	rspObj.Role = roleModel
	rspObj.RoleRes = roleResModel
	rspObj.Token = token
	req.Conn.SetProperty("role", role) //设置当前的角色
	//初始化玩家属性
	err = RoleAttributeService.TryCreate(rid, req)
	if err != nil {
		return common.New(constant.DBError, "数据库错误")
	}
	//初始化玩家城池
	err = RoleCityService.InitCity(role, req)
	if err != nil {
		return common.New(constant.DBError, "数据库错误")
	}
	return nil
}

func (s *roleService) GetRoleRes(rid int) (model.RoleRes, error) {
	roleRes := &data.RoleRes{}
	ok, err := db.Engine.Table(roleRes).Where("rid=?", rid).Get(roleRes)
	if err != nil {
		log.Println("查询角色资源数据库失败")
		return model.RoleRes{}, common.New(constant.DBError, "查询角色资源数据库失败")
	}
	if ok {
		return roleRes.ToModel().(model.RoleRes), nil
	}
	return model.RoleRes{}, nil
}
